package com.hmall.item.aspect;

import cn.hutool.core.util.ObjectUtil;
import com.heima.dto.ItemDTO;
import com.hmall.common.utils.RabbitMqHelper;
import lombok.RequiredArgsConstructor;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import java.lang.reflect.Method;

@Aspect
@Component
@RequiredArgsConstructor
public class SuccessAspectHandler {

    private final RabbitMqHelper rabbitMqHelper;

    /**
     * 切入点：匹配所有标注了@SuccessAspect的方法
     */
    @Around("@annotation(com.hmall.item.aspect.SuccessAspect)")
    public Object aroundSuccessMethod(ProceedingJoinPoint joinPoint) throws Throwable {
        try {
            // 执行目标方法
            Object result = joinPoint.proceed();
            
            // 获取注解信息（如果需要）
            MethodSignature signature = (MethodSignature) joinPoint.getSignature();
            SuccessAspect annotation1 = signature.getMethod().getAnnotation(SuccessAspect.class);
            if(annotation1 != null){
                Object[] args = joinPoint.getArgs();
                ItemDTO itemDTO = null;
                Long id=null;
                if (args.length > 0 && args[0] instanceof ItemDTO) {
                    itemDTO = (ItemDTO) args[0];
                    id = itemDTO.getId();
                }
                if (args.length > 0 && args[0] instanceof Long) {
                    id =(Long)args[0];
                }
                String exchange = annotation1.exchange();
                String routingkey = annotation1.routingkey();
                rabbitMqHelper.sendMessage(exchange,routingkey,id);
            }
            return result;
        } catch (Throwable throwable) {
            // 方法失败时，不执行增强逻辑，直接抛出异常
            System.out.println("方法[" + joinPoint.getSignature().getName() + "]执行发送mq失败：" + throwable.getMessage());
            throw throwable;
        }
    }
}